<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admins;
use App\Models\Users;
use Carbon\Carbon;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Mews\Captcha\Facades\Captcha;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    public function login(Request $request){
        $credentials = $request->only('username','password','captcha','captchaKey');
        $check = Captcha::check_api($credentials['captcha'],$credentials['captchaKey']);
        if(!$check) return $this->writeJson(1,null,'验证码错误');

        //判断用户是否存在
        $user = Admins::select(['id','username','nickname','status'])->where('username',$credentials['username'])->first();
        if(!$user) return $this->writeJson(1,null,'管理员账户不存在');
        if($user['status'] == Admins::STATUS_2) return $this->writeJson(1,null,'管理员账户被锁定,请联系超级管理员');
        $client = new Client();
        $url = request()->root() . '/oauth/token';
        $params = array_merge(config('passport.proxy'), [
            'username' => $credentials['username'],
            'password' => $credentials['password'],
        ]);
        try {
            $response = $client->request('POST', $url, ['form_params' => $params,'guard' => 'admin']);
            $token_info = json_decode($response->getBody()->getContents());
            $user->update(['login_at'=>Carbon::now(),'login_ip'=>$request->getClientIp()]);
            return $this->writeJson(0,['token'=>$token_info->access_token,'userinfo'=>$user],'登录成功,页面即将跳转...');
        } catch (RequestException $exception) {
            return $this->writeJson(1,null,'密码输入错误');
        }
    }


    public function logout()
    {
        if (auth()->guard('api')->check()) {
            auth()->guard('api')->user()->token()->delete();
            return $this->writeJson(0,null,'登出成功,页面即将跳转...');
        }
        return $this->writeJson(1,null,'登出失败');
    }


    public function captcha()
    {
        $captcha = Captcha::create('default', true);
        return $this->writeJson(0,$captcha);
    }

    public function download(Request $request){
        $id = (int)$request->get('id',0);
        if(empty($id)) return $this->writeJson(1,null,'参数错误');
        $info = Users::findOrFail($id);
        if(empty($info['material'])) return $this->writeJson(1,null,'下载的资源不存在');
        return response()->download(public_path().'/'.strrchr($info['material'], "file"));
    }



}